﻿
// #define DISABLE_ATTACHMENT

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Configuration;
using System.Data.SqlClient;
using UDS.Components;
using UDS.Entity;

namespace UDS.SubModule.UnitiveDocument.Mail
{
    /// <summary>
    /// Compose 的摘要说明。
    /// </summary>
    public partial class ComposePage : Page
    {
        protected int ClassID
        {
            get;
            private set;
        }

        protected int MailID
        {
            get;
            private set;
        }

        override protected void OnInit(EventArgs e)
        {
            // Hook event handlers
            btnSendMail.Click += btnSendMail_Click;

            ClassID = QSUtil.GetPositiveInt32("ClassID", 0);
            MailID = QSUtil.GetPositiveInt32("MailID", 0);

            base.OnInit(e);
        }

        protected override void OnLoad(EventArgs e)
        {
            if (!IsPostBack)
            {
                MailAction action = (MailAction)QSUtil.GetPositiveInt32("Action", 0);
                // Session["upattlist"] = upattlist;

                // Action=1 回复 Action=2 转发 Action=3 指定收件人的寄信
                switch (action)
                {
                    case MailAction.Reply:
                        ReplySet(); // 进行回复邮件设置
                        break;

                    case MailAction.Forward:
                        ForwardSet(); // 进行转发邮件设置
                        break;

                    case MailAction.SetReceiver:
                        ReceiverSet(); // 进行发信人设置
                        break;
                }
                PopulateListView();
            }

            base.OnLoad(e);
        }

        #region 回复邮件设置
        /// <summary>
        /// 回复邮件设置
        /// </summary>
        private void ReplySet()
        {
            // 读取原邮件内容
            MailFullInfo mail = UDSMail.GetMailFullInfo(MailID);
            if (mail != null)
            {
                string tmpStr = "<br/>" + mail.Body;
                tmpStr = tmpStr.Replace("<br/>", "\r\n");
                txtSubject.Text = "Re: " + mail.Subject;

                hfSendTo.Value = mail.Sender;
                txtSendTo.Text = mail.SenderRealName;
                txtBody.Text = txtSendTo.Text + "，你好!\r\n\r\n\r\n\r\n";
                txtBody.Text += "=======" + Utility.FormatDateTime(mail.TimeSent) + ", 你在来信中写道:" + "=======\r\n";
                txtBody.Text += tmpStr;
            }
        }
        #endregion

        #region 转发邮件设置
        /// <summary>
        /// 转发邮件设置
        /// </summary>
        private void ForwardSet()
        {
            // 读取原邮件内容
            MailFullInfo mail = UDSMail.GetMailFullInfo(MailID);
            if (mail != null)
            {
                string tmpStr = "<br/>" + mail.Body;
                tmpStr = tmpStr.Replace("<br/>", "\r\n>");
                this.txtSubject.Text = "FW: " + mail.Subject;
                this.txtBody.Text = ",你好!\n\n\n\n\n\n\n";
                this.txtBody.Text += "=======下面是转发邮件=======\n";
                this.txtBody.Text += "原邮件发件人姓名:" + mail.SenderRealName + "\n";
                this.txtBody.Text += "原邮件发件人代号:" + mail.Sender + "\n";
                this.txtBody.Text += tmpStr;
            }

#if false
#if !DISABLE_ATTACHMENT
            using (var dataReader = mailclass.GetMailAttInfoDbreader(MailID.ToString()))
            {
                while (dataReader.Read())
                {
                    UDS.Components.MailAttachFile att = new MailAttachFile();
                    att.FileAttribute = 0;
                    att.FileSize = Int32.Parse(dataReader[1].ToString());
                    att.FileName = dataReader[0].ToString();
                    att.FileAuthor = SiteContext.Current.UserName;
                    att.FileCatlog = "邮件";
                    att.FileVisualPath = dataReader[2].ToString();
                    upattlist.Add(att);
                }
                BindAttList();


                dataReader.Close();
            }
#endif
#endif
        }
        #endregion

        #region 发信人设置
        /// <summary>
        /// 发信人设置
        /// </summary>
        private void ReceiverSet()
        {
            //SendToRealName = (Request.QueryString["Name"] == null) ? "" : Request.QueryString["Name"].ToString() + ",";
            //SendTo = (Request.QueryString["Username"] == null) ? "" : Request.QueryString["Username"].ToString() + ",";
        }
        #endregion

        public string GetClassName()
        {
            if (ClassID == 0)
            {
                return "请选择项目";
            }

            return UDS.Components.ProjectClass.GetProjectName(ClassID);
        }

        #region 初始化下拉列表框
        /// <summary>
        /// 对下拉列表进行初始化
        /// </summary>
        private void PopulateListView()
        {
            cblistAttribute.Items.Clear();
            cblistAttribute.Items.Add(new ListItem("普通邮件", "1"));
            cblistAttribute.Items.Add(new ListItem("邮件归档", "2"));
            //cblistAttribute.Items.Add(new ListItem("结案报告","3"));
            cblistAttribute.Items[0].Selected = true;
        }
        #endregion

#if false
#if !DISABLE_ATTACHMENT
        #region 处理邮件附件上传操作，传回附件数组
        /// <summary>
        /// 处理上传操作,附件以链接形式存放
        /// </summary>
        /// <param name="MailReceiverStr"> 用户登陆名字符串，用逗号隔开 </param>
        private ArrayList AttUpload(string MailReceiverStr)
        {
            HtmlForm FrmCompose = (HtmlForm)this.Page.FindControl("Compose");
            string[] RecvIdAr = System.Text.RegularExpressions.Regex.Split(MailReceiverStr, ",");
            ArrayList listattfile = new ArrayList();
            // 存放附件至发件人目录中，随机生成目录名
            Random TempNameInt = new Random();
            string NewMailDirName = TempNameInt.Next(100000000).ToString();
            string FileName = "";
            try
            {
                var userDirVPath = Utility.CombineVirtualDirs(DocAttachFile.AttachVDir, SiteContext.Current.UserName);
                var userDir = new DirectoryInfo(MapPath(userDirVPath));
                if (!userDir.Exists)
                {
                    userDir.Create();
                }

                var newMailDirVPath = Utility.CombineVirtualDirs(userDirVPath, NewMailDirName);
                Directory.CreateDirectory(MapPath(newMailDirVPath));
                for (int i = 0; i < FrmCompose.Controls.Count; i++)
                {
                    if (FrmCompose.Controls[i].GetType().ToString() == "System.Web.UI.HtmlControls.HtmlInputFile")
                    {
                        HtmlInputFile hif = ((HtmlInputFile)(FrmCompose.Controls[i]));
                        if (hif.PostedFile.FileName.Trim() != "")
                        {
                            FileName = System.IO.Path.GetFileName(hif.PostedFile.FileName);
                            UDS.Components.MailAttachFile att = new MailAttachFile();
                            // 初始化
                            att.FileAttribute = 0;
                            att.FileSize = hif.PostedFile.ContentLength;
                            att.FileName = FileName;
                            att.FileAuthor = SiteContext.Current.UserName;
                            att.FileCatlog = "邮件";
                            att.FileVisualPath = Utility.CombineVirtualDirs(newMailDirVPath, FileName);

                            hif.PostedFile.SaveAs(MapPath(att.FileVisualPath));
                            listattfile.Add(att);
                        }
                    }
                }

            }
            catch (Exception ioex)
            {
                UDS.Components.Logger.Log(ioex.ToString());
                Server.Transfer("../../Error.aspx");
            }


            return listattfile;

        }
        #endregion
#endif
#endif

        #region 处理除收件人外的表单传递参数 传回MailMainBody类
        /// <summary>
        /// 发送不包括附件的邮件正文
        /// </summary>
        private MailFullInfo ProcessFormPost()
        {
            string[] toList = Utility.SplitArray(hfSendTo.Value);
            string[] ccList = Utility.SplitArray(hfCC.Value);
            string[] bccList = Utility.SplitArray(hfBCC.Value);

            if (cblistAttribute.SelectedIndex == -1)
            {
                SiteContext.Current.Alert("请选择邮件类型!", true);
                return null;
            }

            if (cblistAttribute.Items[0].Selected)
            {
                // The TO list is required.
                if (toList == null || toList.Length == 0)
                {
                    SiteContext.Current.Alert("请选择收件人!", true);
                    return null;
                }
            }

            if (cblistAttribute.Items[1].Selected)
            {
                if (Request.Form["hdnProjectID"].ToString() == "0")
                {
                    SiteContext.Current.Alert("请选择归档项目!", true);
                    return null;
                }
            }

            MailFullInfo mail = new MailFullInfo();
            mail.FolderType = MailFolderType.Index; // 放入收件夹
            mail.TOList = Utility.JoinNames(toList);
            mail.CCList = Utility.JoinNames(ccList);
            mail.BCCList = Utility.JoinNames(bccList);
            mail.TimeSent = DateTime.Now;
            mail.Sender = SiteContext.Current.UserName;
            mail.Subject = (txtSubject.Text == "") ? "[无主题]" : txtSubject.Text;
            mail.Body = Transforms.StripScriptTags(txtBody.Text.Replace("\r\n", "<br/>"));
            mail.IsNew = true;
            mail.ClassID = string.IsNullOrEmpty(Request.Form["hdnProjectID"]) ? 0 : int.Parse(Request.Form["hdnProjectID"]);
            mail.Importance = ddlImportance.SelectedImportance;

            //处理短信提醒
            if (cbRemind.Checked)
            {
                List<string> list = new List<string>(256);
                if (toList != null)
                {
                    list.AddRange(toList);
                }
                if (ccList != null)
                {
                    list.AddRange(ccList);
                }
                if (bccList != null)
                {
                    list.AddRange(bccList);
                }

                // Remove duplicate names
                StringComparer comparer = StringComparer.InvariantCultureIgnoreCase;
                list.Sort(comparer);
                for (int i = list.Count - 1; i > 0; i--)
                {
                    if (0 == comparer.Compare(list[i], list[i - 1]))
                    {
                        list.RemoveAt(i);
                    }
                }

                SMS.SendLocalMsg(SiteContext.Current.UserName, list.ToArray(), "您从" + SiteContext.Current.UserName + "处收到了一封新的邮件");
            }

            return mail;
        }
        #endregion

#if false
#if !DISABLE_ATTACHMENT
        #region 文档处理
        /// <summary>
        /// 文档处理处理，包括文档处理及附件处理
        /// </summary>
        private void DocProcess(MailFullInfo mailbody, ArrayList upattlist)
        {
            var canApprove = AssignRights.IsAccessAllowed(SiteContext.Current.UserName, ClassID, PermissionType.ApproveDocument);
            string DocID = "";
            // int cstRightToApproveDocument = 2;
            DocBody docbody = new DocBody();
            docbody.DocTitle = mailbody.Subject;
            docbody.DocContent = mailbody.Body;
            docbody.DocAddedBy = mailbody.Sender;
            docbody.DocClassID = mailbody.ClassID;
            docbody.DocAddedDate = DateTime.Now.ToString();
            docbody.DocApprover = canApprove ? SiteContext.Current.UserName : "";
            docbody.DocApproveDate = canApprove ? DateTime.Now.ToString() : "";
            docbody.DocApproved = (docbody.DocApprover == "") ? 0 : 1;
            docbody.DocAttribute = 0;
            docbody.DocType = 0;

            DocumentClass doc = new DocumentClass();
            // 添加文档,并返回ID

            DocID = doc.AddDocBody(docbody);
            foreach (UDS.Components.MailAttachFile att in upattlist)
            {
                DocAttachFile docatt = new DocAttachFile();
                //  Mail Attach File 类转换为Doc Attach File
                docatt.FileAttribute = 0;
                docatt.FileSize = att.FileSize;
                docatt.FileName = att.FileName;
                docatt.FileAuthor = SiteContext.Current.UserName;
                docatt.FileCatlog = "文档";
                docatt.FileVisualPath = "Mail" + att.FileVisualPath;
                docatt.FileAddedDate = DateTime.Now.ToString();
                docatt.DocID = Int32.Parse(DocID);
                // 转换结束


                // 附件数据库处理
                doc.AddAttach(docatt, Int32.Parse(DocID));
            }

        }
        #endregion
#endif
#endif

        /// <summary>
        /// 发信处理，包括邮件处理及附件处理
        /// </summary>
        private void btnSendMail_Click(object sender, System.EventArgs e)
        {
            // MailClass mailclass = new UDS.Components.MailClass();
            // MailMainBody mailbody = new UDS.Components.MailMainBody();
            // ArrayList upattlist = (ArrayList)Session["upattlist"];
            //	ArrayList listattfile = new ArrayList();
            MailFullInfo mailbody = ProcessFormPost();
            UDSMail.SendMail(mailbody, fileUploader.Files, cbSMS.Checked); // 返回已经发送的邮件ID列表(包括抄送和密抄)

#if false
#if !DISABLE_ATTACHMENT
                foreach (string mailID in listmail)
                {   // 循环发送邮件附件
                    foreach (UDS.Components.MailAttachFile att in upattlist)
                    {   //　处理邮件附件的数据库操作部分 

                        Random TempNameInt = new Random();
                        string NewDocDirName = TempNameInt.Next(100000000).ToString();

                        var newDocDirVPath = Utility.CombineVirtualDirs(DocAttachFile.AttachVDir, SiteContext.Current.UserName + "/" + NewDocDirName);
                        var newDocDir = new DirectoryInfo(MapPath(newDocDirVPath));
                        if (!newDocDir.Exists)
                        {
                            newDocDir.Create();
                        }
                        File.Copy(MapPath(att.FileVisualPath), Path.Combine(newDocDir.FullName, att.FileName), true);

                        att.FileVisualPath = Utility.CombineVirtualDirs(newDocDirVPath, att.FileName);
                        mailclass.AttSend(att, Int32.Parse(mailID));
                    }
                }

                if (cblistAttribute.Items[1].Selected && Request.Form["hdnProjectID"].ToString() != "0")
                {
                    DocProcess(mailbody, upattlist);
                }
#endif
#endif

            const string backScript = @"
if(window.parent.frames.length===0){
  window.close();
}else{
  window.self.location=(""Index.aspx"");
}";
            SiteContext.Current.Alert("邮件发送成功!", backScript, true);
        }

#if false
#if !DISABLE_ATTACHMENT
        private void BindAttList()
        {

            this.listUp.Items.Clear();
            int count = 0;
            ArrayList upattlist = (ArrayList)Session["upattlist"];
            foreach (UDS.Components.MailAttachFile att in upattlist)
            {
                count++;
                this.listUp.Items.Add(new ListItem(att.FileName.ToString(), count.ToString()));

            }

        }

        private void btnUpload_Click(object sender, System.EventArgs e)
        {
            HtmlForm FrmCompose = (HtmlForm)this.Page.FindControl("Compose");
            Random TempNameInt = new Random();
            string NewMailDirName = TempNameInt.Next(100000000).ToString();
            // 存放附件至提交人目录中，随机生成目录名
            ArrayList upattlist = (ArrayList)Session["upattlist"];
            string FileName = "";
            try
            {
                var tmpDirVPath = Utility.CombineVirtualDirs(DocAttachFile.TempAttachVDir, SiteContext.Current.UserName + '-' + NewMailDirName);
                var tmpDir = new DirectoryInfo(MapPath(tmpDirVPath));
                if (!tmpDir.Exists)
                {
                    tmpDir.Create();
                }

                for (int i = 0; i < FrmCompose.Controls.Count; i++)
                {
                    if (FrmCompose.Controls[i].GetType().ToString() == "System.Web.UI.HtmlControls.HtmlInputFile")
                    {

                        HtmlInputFile hif = ((HtmlInputFile)(FrmCompose.Controls[i]));
                        if (hif.PostedFile.FileName.Trim() != "")
                        {
                            FileName = System.IO.Path.GetFileName(hif.PostedFile.FileName);
                            UDS.Components.MailAttachFile att = new MailAttachFile();
                            // 初始化
                            att.FileAttribute = 0;
                            att.FileSize = hif.PostedFile.ContentLength;
                            att.FileName = FileName;
                            att.FileAuthor = SiteContext.Current.UserName;
                            att.FileCatlog = "邮件";
                            att.FileVisualPath = Utility.CombineVirtualDirs(tmpDirVPath, FileName);
                            hif.PostedFile.SaveAs(MapPath(att.FileVisualPath));
                            upattlist.Add(att);

                        }
                        hif = null;
                    }
                }
                Session["upattlist"] = upattlist;
                BindAttList();
                this.SendToRealName = Request.Form["txtSendTo"].ToString();
                this.SendTo = Request.Form["hdnTxtSendTo"].ToString();
                this.CcTo = Request.Form["hdnTxtCcTo"].ToString();
                this.BccTo = Request.Form["hdnTxtBccTo"].ToString();
                this.CcToRealName = Request.Form["txtCcTo"].ToString();
                this.BccToRealName = Request.Form["txtBccTo"].ToString();
            }
            catch (Exception ioex)
            {
                UDS.Components.Logger.Log(ioex.ToString());
                Server.Transfer("../../Error.aspx");
            }




        }

        private void btnRemove_Click(object sender, System.EventArgs e)
        {
            ArrayList upattlist = (ArrayList)Session["upattlist"];
            for (int i = listUp.Items.Count - 1; i >= 0; i--)
            {
                if (this.listUp.Items[i].Selected)
                {
                    this.listUp.Items.RemoveAt(i);
                    upattlist.RemoveAt(i);
                }
            }

            Session["upattlist"] = upattlist;
            this.SendToRealName = Request.Form["txtSendTo"].ToString();
            this.SendTo = Request.Form["hdnTxtSendTo"].ToString();
            this.CcTo = Request.Form["hdnTxtCcTo"].ToString();
            this.BccTo = Request.Form["hdnTxtBccTo"].ToString();
            this.CcToRealName = Request.Form["txtCcTo"].ToString();
            this.BccToRealName = Request.Form["txtBccTo"].ToString();
        }
#endif
#endif
    }
}
